<template>
  <div>
    <a-spin :spinning="spinning">
      <input
        type="file"
        multiple
        id="files"
        ref="refFile"
        style="display: none"
        v-on:change="fileLoad"
      />
      <div v-if="station" style="margin: 20px 0 0 0">
        <sync-model-dlg ref="syncDlg"></sync-model-dlg>
        <a-space>
          <a-button @click="addThing">增加设备...</a-button>
          <a-button v-if="isEdge" @click="syncToCloud">同步到云端...</a-button>
          <a-button @click="deleteThings">批量删除</a-button>
          <a-button @click="importThings">批量导入...</a-button>

          <!--<a-button @click="exportThings">批量导出...</a-button>-->

          <a-button @click="refresh">刷新</a-button>
          <finder @gotoItem="gotoItem"></finder>

          <!--
        <a-button @click="refresh" style="margin: 0 0 0 30px"
          >下载模板</a-button
        >-->
        </a-space>
        <p style="margin: 10px 0 0 0">
          <template v-for="(column, index) in columns">
            <vxe-checkbox
              v-if="column.title"
              v-model="column.visible"
              :key="index"
              @change="$refs.xTree.refreshColumn()"
              >{{ column.title }}</vxe-checkbox
            >
          </template>
        </p>
        <thing-cfg-dlg ref="thingDlg"></thing-cfg-dlg>
        <vxe-table
          style="margin: 10px 0 0 0"
          :height="theight"
          size="small"
          ref="xTree"
          border="inner"
          stripe
          highlight-current-row
          :data="station.devs"
          @current-change="currentChangeEvent"
          @cell-dblclick="cellDBLClickEvent"
          :checkbox-config="{
            checkField: 'checked',
            highlight: false,
            range: true,
          }"
          :row-config="{ isCurrent: true, isHover: true }"
          :column-config="{ resizable: true }"
        >
          <vxe-table-column type="seq" width="60"></vxe-table-column>
          <vxe-table-column type="checkbox" width="60"></vxe-table-column>
          <vxe-table-column
            width="100"
            field="s_name"
            title="名称"
            sortable
            :filters="[{ data: '' }]"
            :filter-method="filterNameMethod"
            :filter-recover-method="filterNameMethod"
          >
            <template #filter="{ $panel, column }">
              <template v-for="(option, index) in column.filters">
                <input
                  class="my-input"
                  type="type"
                  :key="index"
                  v-model="option.data"
                  @input="$panel.changeOption($event, !!option.data, option)"
                  @keyup.enter="$panel.confirmFilter()"
                  placeholder="按回车确认筛选"
                />
              </template>
            </template>
          </vxe-table-column>
          <vxe-table-column
            field="uid"
            title="ID"
            sortable
            show-overflow="title"
          >
          </vxe-table-column>
          <vxe-table-column
            field="model_name"
            title="物模型"
            show-overflow
            sortable
          >
          </vxe-table-column>
          <vxe-table-column field="sno" title="同类编号" sortable>
          </vxe-table-column>
          <vxe-table-column
            field="used_time"
            title="启用时间"
            show-overflow="title"
            show-header-overflow
          >
          </vxe-table-column>
          <vxe-table-column
            field="buy_time"
            title="购买时间"
            show-overflow="title"
            show-header-overflow
          >
          </vxe-table-column>
          <vxe-table-column
            field="create_time"
            title="创建时间"
            show-overflow="title"
            show-header-overflow
          >
          </vxe-table-column>

          <vxe-table-column field="ip" title="IP" sortable width="120">
          </vxe-table-column>
          <vxe-table-column field="business_id" title="sn" sortable>
          </vxe-table-column>
          <vxe-table-column
            field="status_used"
            title="开通状态"
            :formatter="formatterStatus"
            :filters="[{ data: '' }]"
            :filter-method="filterStatusMethod"
          >
            <template #filter="{ $panel, column }">
              <select
                class="my-select"
                v-model="option.data"
                v-for="(option, index) in column.filters"
                :key="index"
                @change="$panel.changeOption($event, !!option.data, option)"
              >
                <option v-for="s in statusList" :key="s.value" :value="s.label">
                  {{ s.label }}
                </option>
              </select>
            </template>
          </vxe-table-column>
          <vxe-table-column
            field="state"
            title="在线状态"
            :formatter="formatterState"
            :filters="stateList"
            :filter-multiple="false"
          ></vxe-table-column>

          <vxe-table-column field="lon" title="经度"> </vxe-table-column>
          <vxe-table-column field="lat" title="纬度"> </vxe-table-column>
          <vxe-table-column
            field="is_proxy"
            title="直连"
            :formatter="formatterTrueFalse"
          >
          </vxe-table-column>
          <vxe-table-column title="操作" width="120" show-overflow>
            <template #default="{ row }">
              <a-space>
                <a-icon type="edit" @click="editThing(row)" />
                <a-icon type="bell" @click="alarmLimitEdit(row)" />
                <a-icon type="redo" @click="forceData(row)" />
                <a-icon type="database" @click="testData(row)" />
                <a-popconfirm
                  title="是否确认删除该记录？"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="removeDev(row)"
                >
                  <a-icon type="delete" />
                </a-popconfirm>
              </a-space>
            </template>
          </vxe-table-column>
        </vxe-table>
      </div>
    </a-spin>
  </div>
</template>
<script>
import { post, update, remove, postEx } from "@/services/crud";
import { forceData } from "@/services/dataAPI";
import ThingCfgDlg from "../dcfg/ThingCfgDlg.vue";
import SyncModelDlg from "@/components/cfg/sync/SyncModelDlg.vue";
import { handleExcel } from "@/services/importCfg.js";
import Finder from "@/components/cfg/dcfg/Finder";
function createByFun(fun, citem) {
  return new Promise((re, rej) => {
    let url = "thing";
    if (fun == post) {
      url = "newDev";
    }
    fun(url, citem).then((res) => {
      console.log("***************", res);
      if (res && res.data && res.data.result) {
        citem.uid = res.data.result.uid;
      }
      if (fun == post) {
        re();
        return;
      }
      if (citem.station) {
        console.log(citem);
        fun("thingstation", {
          thing_id: citem.uid,
          station_id: citem.station.uid,
        })
          .catch((err) => {
            rej(err);
          })
          .then(() => {
            //let itemparams = item.params
            let setParams = {
              thing_id: citem.uid,
              values: citem.params,
            };
            fun("thingparam", setParams);
            re();
          })
          .catch((err) => {
            rej(err);
          });
      }
    });
  });
}
export default {
  components: {
    ThingCfgDlg,
    SyncModelDlg,
    Finder,
  },
  computed: {
    station() {
      return this.$store.state.station.activeStation;
    },

    isEdge() {
      return process.env.VUE_APP_TYPE === "edge";
    },
    theight() {
      return document.body.clientHeight - 280 + "px";
    },
  },
  mounted() {
    // 获取所有列配置
    let self = this;
    setTimeout(() => {
      self.columns = self?.$refs?.xTree?.getColumns();
      if (self.columns.length >= 10) {
        self.columns[10].visible = false;
      }

      self.refresh();
      self.$refs.xTree.refreshColumn();
    }, 1000);
  },
  data() {
    return {
      spinning: false,
      stateList: [
        { label: "在线", value: 1 },
        { label: "离线", value: 0 },
      ],
      /*  <span v-if="record.status_used === -2">未知</span>
            <span v-if="record.status_used === 1">使用中</span>
            <span v-if="record.status_used === 0">停用</span>
            <span v-if="record.status_used === -1">施工中</span>*/
      statusList: [
        { label: "启用", value: 1 },
        { label: "停用", value: 0 },
        { label: "施工中", value: 2 },
        { label: "未知", value: -2 },
      ],
      columns: [],
    };
  },
  methods: {
    gotoItem(item) {
      this.$emit("gotoItem", item);
      let self = this;
      setTimeout(() => {
        if (self.station?.devs) {
          let dev = self.station.devs.find((dev) => {
            return dev.uid == item.uid;
          });
          if (dev) {
            self.$refs.xTree.setCurrentRow(dev);
          }
        }
      }, 500);
    },
    testData(row) {
      this.$router.push({ path: "/data/tester", query: { target: row } });
    },
    alarmLimitEdit(row) {
      this.$router.push({ path: "alarmcfg", query: { thing: row } });
    },
    forceData() {
      forceData();
    },
    importThings() {
      this.$refs.refFile.value = "";
      this.$refs.refFile.dispatchEvent(new MouseEvent("click"));
    },
    fileLoad() {
      let self = this;
      this.$refs.refFile.files.forEach((selectedFile) => {
        var reader = new FileReader();
        //const record = this.currentRecord
        console.log("XXXXXXXXXXXXXXXXXXXX", selectedFile);
        handleExcel(
          selectedFile,
          (s) => {
            console.log("----------------------handle sheet------", s);
            return true;
          },
          (datas) => {
            postEx(
              "/cfg/fromFile/import/" + self.station.model_id,
              datas
            ).finally(() => {
              self.refresh();
            });
          }
        );
      });
      this.$refs.refFile.value = "";
      //const selectedFile = this.$refs.refFile.files[0];
    },
    currentChangeEvent(row) {
      console.log("**************", row);
    },
    exportThings() {},
    filterNameMethod({ option, row }) {
      return row.s_name.indexOf(option.data) >= 0;
    },
    filterStatusMethod({ option, row }) {
      let value = row.status_used;
      let label = this.formatterStatus({ cellValue: value });
      return label == option.data;
    },
    formatterState({ cellValue }) {
      let index = this.stateList.findIndex((s) => {
        return s.value == cellValue;
      });
      if (index == -1) {
        return "未知";
      }
      return this.stateList[index].label;
    },
    formatterTrueFalse({ cellValue }) {
      if (cellValue == true || cellValue == "true" || cellValue == 1) {
        return "是";
      }
      return "否";
    },
    formatterStatus({ cellValue }) {
      let index = this.statusList.findIndex((s) => {
        return s.value == cellValue;
      });
      if (index == -1) {
        return "未知";
      }
      return this.statusList[index].label;
    },
    thingsToCloud(child) {
      var edge;
      this.station.devs.forEach((dev) => {
        if (dev.model_id == "IOTBASEmEdgeCTL") {
          edge = dev;
        }
      });
      if (edge) {
        //{ things, pd, un, edgeID,addr }
        return this.$store.dispatch("station/syncStationToCloud", {
          edgeID: edge.uid,
          things: this.station.devs,
          un: child.username,
          pd: child.password,
          addr: child.svrAddr,
        });
      }
    },
    syncToCloud() {
      this.$refs.syncDlg.showDlg(this.thingsToCloud);
    },
    async thingAction(fun, owner, item, count) {
      //const item = dlg.$data.item
      const _this = owner;
      if (count == undefined) {
        count = 1;
      }
      let name = item.s_name;
      if (!name) {
        name = item.model_id;
      }
      this.spinning = true;
      item.station_id = this.station.uid;
      let sitem = JSON.stringify(item);
      let citem = JSON.parse(sitem);

      citem.count = count;
      try {
        await createByFun(fun, citem);
      } catch (err) {
        console.log("----------------create fun------", err);
      }

      this.spinning = false;
      this.refresh();
    },
    refresh() {
      this.spinning = true;
      let _this = this;
      this.$store.dispatch("station/refreshActiveStation").finally(() => {
        _this.spinning = false;
      });
    },
    cellDBLClickEvent({ row }) {
      this.editThing(row);
    },
    addThingToSvr(owner, dlg) {
      const item = dlg.$data.citem;
      const count = dlg.$data.count;
      console.log("add item--------------", item);
      return owner.thingAction(post, owner, item, count);
    },
    updateThingToSvr(owner, dlg) {
      const item = dlg.$data.citem;
      console.log("update item--------------", item);
      return owner.thingAction(update, owner, item);
    },
    addThing() {
      //this.curStation = record;
      //console.log("-------------", record);
      this.spinning = true;
      this.$refs.thingDlg.Show(this.addThingToSvr, this, {
        isNew: true,
        station: this.station,
      });
      this.spinning = false;
    },
    editThing(child) {
      //this.curStation = record;
      //console.log("-------------", record);
      this.spinning = true;
      const item = JSON.parse(JSON.stringify(child)); //Object.assign({}, child);
      item.isNew = false;
      item.station = this.station;
      this.$refs.thingDlg.Show(this.updateThingToSvr, this, item);
      this.spinning = false;
    },
    removeDev(child) {
      let _this = this;
      this.spinning = true;
      remove("thing", child.uid).finally(() => {
        _this.refresh();
        _this.spinning = false;
      });
    },
    saveColumns() {
      let infos = this.$refs.xTree.getColumns().map((x) => {
        return {
          visible: x.visible,
          title: x.title,
        };
      });
      let item = { body: infos, c_type: "user", s_name: "devlist.columns" };
      saveCustom(item);
    },
    deleteThings() {
      let devs = [];

      this.station.devs.forEach((dev) => {
        if (dev.checked) {
          devs.push(
            new Promise((re) => {
              remove("thing", dev.uid).finally(() => {
                re();
              });
            })
          );
        }
      });
      let self = this;
      if (devs.length > 0) {
        this.spinning = true;
        Promise.all(devs).finally(() => {
          self.spinning = true;
          self.refresh();
        });
      }
    },
  },
};
</script>
<style scoped>
.vxe-table--render-default .vxe-body--row.row--current{background:rgb(147, 235, 135)}
</style>